require 'rails/generators'
require 'fileutils'

module SimplyMongo
  module Generators
    class InstallGenerator < ::Rails::Generators::Base
      source_root File.expand_path("../templates", __FILE__)
      desc "This will install the template mongo.yml and the SimplyMongo Initializer file"

      def install
        config_dir   = "#{Rails.root}/config"

        mongo_yml    = "mongo.yml"
        working_file = "#{config_dir}/#{mongo_yml}"
        if File.exists? working_file
          simply_mongo_back_up_file(working_file, mongo_yml)
        end
        copy_file mongo_yml, working_file
        puts "Now Configure #{Rails.root}/config/#{mongo_yml}"
        
        mongo_rb     = "mongo.rb"
        working_file = "#{config_dir}/initializers/#{mongo_rb}"
        if File.exists? working_file
          simply_mongo_back_up_file(working_file, mongo_rb)
        end
        copy_file mongo_rb, working_file
      end
      
      private
      
        def simply_mongo_back_up_file(working_file, new_file)
          mv_time =  DateTime.now.strftime("%Y%m%d%H%M%S%L")
          mf      = "#{working_file}_#{mv_time}"
          puts "WARNING: ** Backing up existing #{new_file} to #{File.basename(mf)}"
          FileUtils.mv working_file, mf
        end
      
    end
  end
end